package com._21cn.framework.utils;

import com._21cn.framework.cache.Cache;
import com._21cn.framework.cache.SimpleCache;

import java.io.*;
import java.util.*;

/**
 * properties文件工具类
 * Created by 司徒海富 on 2017/2/6.
 */
public class PropertyUtil {

    private static Cache cache = new SimpleCache().init();

    /**
     * 获取配置文件中的内容
     * @param fileName  classPath下的文件路径
     * @param charSet
     * @return
     */
    public static Map<String, String> getProperties(String fileName, String charSet){
        Map<String, String> results = (Map<String, String>)cache.get(fileName);
        if( results == null ){
            results = new HashMap();
            InputStream inputStream = null;
            try {
                ClassLoader classLoader = PropertyUtil.class.getClassLoader();
                inputStream = classLoader.getResourceAsStream(fileName);
                if( inputStream!=null ){
                    Properties p = new Properties();
                    p.load(inputStream);
                    Enumeration en = p.propertyNames();
                    while (en.hasMoreElements()){
                        String tempKey = en.nextElement().toString();
                        String key = new String(tempKey.getBytes("ISO-8859-1"),charSet);
                        String value = new String(p.getProperty(tempKey).getBytes("ISO-8859-1"),charSet);
                        results.put(key,value);
                    }
                    cache.put(fileName, results);       //设置缓存
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally{
                if (inputStream != null){
                    try {
                        inputStream.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }

        return results;
    }

    /**
     * 根据配置文件的key，获取配置值
     * @param fileName
     * @param key
     * @return
     */
    public static String getProperty(String fileName,String key){
        Map<String, String> properties = getProperties(fileName, "utf8");
        String property = properties.get(key);
        return property;
    }

}
